package com.zhongxi.guoyuan.view.shopCart;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.shopCart.AddressListAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.shopcart.AddressListResult;
import com.zhongxi.guoyuan.url.Url;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddressListActivity extends BaseActivity implements View.OnClickListener {

    private PullToRefreshListView lvList;
    private List<AddressListResult.AddressListData> list = new ArrayList<AddressListResult.AddressListData>();
    private AddressListAdapter adapter;
    private String type;
    private TextView tvComplete;
    private TextView tvAdd;

    private Map<String, String> map = new HashMap<String, String>();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            deleteAddress(msg.what);
        }
    };
    private AddressListResult result;

    /**
     * 删除地址
     * @param pos
     */
    private void deleteAddress(int pos) {
        type = "delete";
        map.clear();
        map.put("aid", result.getData().get(pos).getId());
        getServer(Url.DELETE_ADDRESS, map, "", false, null, "post");
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_address_list);
        initTitle();
        tvTitle.setText("收货地址");
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        tvAdd = (TextView) findViewById(R.id.tvAdd);
        tvComplete = (TextView) findViewById(R.id.tvComplete);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new AddressListAdapter(this, list, handler);
        lvList.setAdapter(adapter);
        addressList();
    }

    /**
     * 获取地址列表
     */
    private void addressList() {
        type = "addresslist";
        getServer(Url.ADDRESS_LIST, null, "", false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvAdd.setOnClickListener(this);
        tvComplete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvAdd:
//                startAct(EditAddressActivity.class);
                Intent intent = new Intent(context, EditAddressActivity.class);
                startActivityForResult(intent,100);
                break;
            case R.id.tvComplete:
                //设置默认地址
                if(adapter.getSelectPos()!=-1){
                    setDefaultAddress();
                }else {
                    finish();
                }
                break;
        }
    }

    /**
     * 设置默认配送地址
     */
    private void setDefaultAddress() {
        type = "default";
        String str = "&aid="+list.get(adapter.getSelectPos()).getId();
        getServer(Url.DEFAULT_ADDRESS, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try{
            Gson gson = new Gson();
            if("addresslist".equals(type)) {
                result = gson.fromJson(response, AddressListResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                list.clear();
                if(null!=result.getData()&&result.getData().size()>0){
                    list.addAll(result.getData());
                }else{
                    SharedPreferences sp = context.getSharedPreferences(Url.APP_SP, Context.MODE_PRIVATE);
                    sp.edit().putString("name", "").commit();
                    sp.edit().putString("userphone", "").commit();
                    sp.edit().putString("address", "").commit();
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            }else if("default".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("默认地址设置成功");
                addressList();
            }else if("delete".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("删除地址成功！");
                addressList();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        try{
            Gson gson = new Gson();
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        addressList();
    }
}
